package com.ruoyi.pos.web.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.enums.SalesTypeEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.weCat.WeCatUtils;
import com.ruoyi.common.utils.weCat.template.ShipTemplate;
import com.ruoyi.pos.api.vo.user.TerminalInfoVo;
import com.ruoyi.pos.web.domain.TOrderSnInfo;
import com.ruoyi.pos.web.domain.TTerminalInfo;
import com.ruoyi.pos.web.domain.TUserInfo;
import com.ruoyi.pos.web.mapper.TOrderSnInfoMapper;
import com.ruoyi.pos.web.service.ITOrderSnInfoService;
import com.ruoyi.pos.web.service.ITTerminalInfoService;
import com.ruoyi.pos.web.service.ITUserInfoService;
import jdk.nashorn.internal.ir.Terminal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import com.ruoyi.pos.web.mapper.TOrderInfoMapper;
import com.ruoyi.pos.web.domain.TOrderInfo;
import com.ruoyi.pos.web.service.ITOrderInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-15
 */
@Service
public class TOrderInfoServiceImpl implements ITOrderInfoService {
    @Autowired
    private TOrderInfoMapper tOrderInfoMapper;
    @Autowired
    private ITTerminalInfoService terminalInfoService;
    @Autowired
    private ITOrderSnInfoService orderSnInfoService;
    @Autowired
    private TOrderSnInfoMapper tOrderSnInfoMapper;
    @Autowired
    private WeCatUtils weCatUtils;
    @Autowired
    private ITUserInfoService userInfoService;
    @Autowired
    Environment env;
    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TOrderInfo selectTOrderInfoById(String id) {
        return tOrderInfoMapper.selectTOrderInfoById(id);
    }

    /**
     * 查询订单列表
     *
     * @param tOrderInfo 订单
     * @return 订单
     */
    @Override
    public List<TOrderInfo> selectTOrderInfoList(TOrderInfo tOrderInfo) {
        return tOrderInfoMapper.selectTOrderInfoList(tOrderInfo);
    }

    /**
     * 新增订单
     *
     * @param tOrderInfo 订单
     * @return 结果
     */
    @Override
    public int insertTOrderInfo(TOrderInfo tOrderInfo) {
        tOrderInfo.setCreateTime(DateUtils.getNowDate());
        return tOrderInfoMapper.insertTOrderInfo(tOrderInfo);
    }

    /**
     * 修改订单
     *
     * @param tOrderInfo 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTOrderInfo(TOrderInfo tOrderInfo) {
        return tOrderInfoMapper.updateTOrderInfo(tOrderInfo);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderInfoByIds(String[] ids) {
        return tOrderInfoMapper.deleteTOrderInfoByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderInfoById(String id) {
        return tOrderInfoMapper.deleteTOrderInfoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ship(TOrderInfo tOrderInfo) {
        if (StringUtils.isNotEmpty(tOrderInfo.getBrandId())){
            String snCodes = tOrderInfo.getSnCodes();
            if (StringUtils.isNotEmpty(snCodes)){
                String[] snCodeArray = snCodes.split("\n");
                String join = String.join(",", snCodeArray);
                Set set= new HashSet<>(Arrays.asList(snCodeArray));
                if (set.size()!=snCodeArray.length){
                    throw new IllegalArgumentException("重复的sn码");
                }
//                查询订单信息
                TOrderInfo orderInfo = tOrderInfoMapper.selectTOrderInfoById(tOrderInfo.getId());
                if (orderInfo.getGoodsNum().compareTo(new BigDecimal(set.size()))!=0){
                    throw new IllegalArgumentException("终端数量不对");
                }
                List<TOrderSnInfo> tOrderSnInfos = tOrderSnInfoMapper.selectSnCode(snCodeArray);
                if ( StringUtils.isNotNull(tOrderSnInfos) && tOrderSnInfos.size() > 0){
                    List<String> codeList = new ArrayList<>();
                    for (TOrderSnInfo info : tOrderSnInfos) {
                        codeList.add(info.getSnCode());
                    }
                    throw new IllegalArgumentException("请勿重复发布"+String.join("\n",codeList));
                }

                TTerminalInfo terminalInfo = new TTerminalInfo();
                terminalInfo.setSnCodes(join);
                terminalInfo.setBrandId(orderInfo.getBrandId());//查询终端的品牌
                terminalInfo.setSellStatus(SalesTypeEnums.Not_SOLD.getCode());//查询未出售的SN码
                List<TTerminalInfo> terminalInfoList = terminalInfoService.selectTTerminalInfoList(terminalInfo);
                if (terminalInfoList.size()!=snCodeArray.length){
                    throw new IllegalArgumentException("请先维护此SN码");
                }
                TOrderSnInfo snInfo = new TOrderSnInfo();
                snInfo.setOrderId(tOrderInfo.getId());
                orderSnInfoService.delete(snInfo);
                orderSnInfoService.insert(tOrderInfo.getId(),snCodeArray);
            }else {
                throw new IllegalArgumentException("SN码不能为空");
            }
        }
        TUserInfo tUserInfo = userInfoService.selectTUserInfoByUserId(tOrderInfo.getUserId());
        try {
            JSONObject first = new JSONObject();
            first.put("value", "终极测试消息模板-再来一下");
            JSONObject delivername = new JSONObject();
            delivername.put("value", "京东物流");
            JSONObject ordername = new JSONObject();
            ordername.put("value", "测试OrderNo");
            JSONObject remark = new JSONObject();
            remark.put("value", "发货啦");
            ShipTemplate.Params data = ShipTemplate.Params.builder()
                    .first(first)
                    .delivername(delivername)
                    .ordername(ordername)
                    .remark(remark)
                    .build();
            ShipTemplate template = ShipTemplate.builder()
                    .template_id(env.getProperty("wx.template.refuseTemplate"))
                    .touser(tUserInfo.getOpenId())
                    .url("https://www.baidu.com/")
                    .data(data)
                    .build();
            weCatUtils.sendTemplate(template);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tOrderInfoMapper.updateTOrderInfo(tOrderInfo);
    }
    /*查询订单兑换记录*/
    @Override
    public List<TOrderInfo> exchangeOrderList(TOrderInfo tOrderInfo){
        return  tOrderInfoMapper.exchangeOrderList(tOrderInfo);
    }

}
